package com.ttmusic.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.ttmusic.comparator.LrcComparator;
import com.ttmusic.core.MusicManager;
import com.ttmusic.entity.AbstractMusic;
import com.ttmusic.entity.LrcContent;
import com.ttmusic.entity.MusicInfo;

import android.content.Context;
import android.os.Environment;



/**
 * 歌词工具类
 * @author wuchangyong
 *
 */
public class LrcUtil {
	
	
	//歌词文件保存的根路径
    public static final String lrcRootPath = Environment.getExternalStorageDirectory().toString()
            + "/Music/Musiclrc/";

    /**
     * 从本地读取歌词
     *
     * @param music
     * @return
     */
    public static List<LrcContent> loadLocalLrc(Context context) {
        List<LrcContent> lrclists = new ArrayList<LrcContent>();
        AbstractMusic imusic = MusicManager.getNowPlayingSong();
        if (imusic.getType() == AbstractMusic.MusicType.Local) {
        	File file = new File(lrcRootPath);
            if(!file.exists()) {
            	//文件夹不存在 直接返回
            	return lrclists;
            }
        	MusicInfo music = (MusicInfo)imusic;
        	String title = music.getTitle();		//歌曲名称 不带歌手名称 不带后缀
            String artist = music.getArtist();	//歌手名称
            String lrcName = "";
            if(title.indexOf("-") >= 0) {
            	String titleTrim = "";
            	String[] ss = title.split("-");
            	//有可能歌曲名称里面包含多个-符号
            	for(int i=0;i<ss.length;i++) {
            		titleTrim += ss[i].trim() + "-";
            	}
            	if(title.endsWith("-")) {
            		titleTrim = titleTrim.substring(0, titleTrim.length()-1);
            	}
            	title = titleTrim.trim();
            }
            //包含括号的不正规名称
        	if(title.contains("(") && title.contains(")")) {
        		title = title.substring(0, title.indexOf("(")).trim();
        	}
            lrcName = artist + "-" + title + ".lrc";
            //Toast.makeText(context, "加载本地歌词--" + lrcRootPath + lrcName + " 共 " + lrclists.size() + " 行", Toast.LENGTH_LONG).show();
            
            file = new File(lrcRootPath + lrcName); //.toLowerCase()

            
        	FileInputStream fin = null;
        	BufferedReader br = null;
            try {
            	if (file.exists()) {
                    fin = new FileInputStream(file);
                    br = new BufferedReader(new InputStreamReader(fin, "utf-8"));

                    String s;
                    while ((s = br.readLine()) != null) {
                    	handleEachLine(s, lrclists);
                    }
                    // 按时间排序
                    Collections.sort(lrclists, new LrcComparator());
            	}
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
				try {
					if(null != br) br.close();
					if(null != fin) fin.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
        }
        return lrclists;
    }


    /**
     * 解析歌词内容字符串
     * @param lrcContent
     * @return
     */
    public static List<LrcContent> parseLrcStr(String lrcContent) {
        List<LrcContent> lrclists = new ArrayList<LrcContent>();
        String lines[] = lrcContent.split("\n");
        for (String line : lines) {
        	handleEachLine(line, lrclists);
        }
        return lrclists;
    }

    /**
     * 利用正则表达式解析歌词时间和内容   格式为    [00:27.37]在那些苍翠的路上
     * @param line 歌词文件中的每一行内容
     * @param lrclists
     */
    static void handleEachLine(String line, List<LrcContent> lrclists) {
        String s = line.replace("[", ""); // 去掉左边括号
        String lrcData[] = s.split("]");

        // 这句是歌词
        if (lrcData[0].matches("^\\d{2}:\\d{2}.\\d+$")) {
            int len = lrcData.length;
            int end = lrcData[len - 1].matches("^\\d{2}:\\d{2}.\\d+$") ? len : len - 1;

            for (int i = 0; i < end; i++) {
                LrcContent lrcContent = new LrcContent();
                int lrcTime = TimeUtil.getLrcMillTime(lrcData[i]);
                lrcContent.setLrcTime(lrcTime);
                if (lrcData.length == end)
                    lrcContent.setLrcStr(""); // 空白行
                else
                    lrcContent.setLrcStr(lrcData[len - 1].trim());

                lrclists.add(lrcContent);
            }

        }
    }

    /**
     * 将歌词内容字符串保存到本地
     * @param title
     * @param artist
     * @param lrcContext
     */
    public static void writeLrcToLocal(String title, String artist, String lrcContext) {
        FileWriter writer = null;
        try {
            File file = new File(lrcRootPath);
            if(!file.exists()) {
            	file.mkdirs();//第一次自动创建文件夹
            }
            file = new File(getLrcPath(title, artist));
            if (!file.exists()) {
                file.createNewFile();
                writer = new FileWriter(file);
                writer.write(lrcContext);
                writer.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 根据歌名和艺术家生产的系统默认歌词文件位置路径
     *
     * @param title
     * @param artist
     * @return
     */
    public static String getLrcPath(String artist, String title) {
        return lrcRootPath + artist + " - " + title + ".lrc";
    }
}
